<?php defined('SYSPATH') or die('No direct script access.');
 
class Controller_User extends Controller_Template {
 
    public function action_index()
    {
		session_start();
    	$this->_config = Kohana::$config->load('twitter');
    	// TwitterOAuth instance, with two new parameters we got in twitter_login.php
		$twitteroauth = new TwitterOAuth($this->_config->get('consumer_key'), $this->_config->get('consumer_secret'), $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
		// Let's request the access token
		$access_token = $twitteroauth->getAccessToken($_GET['oauth_verifier']);
		// Save it in a session var
		$_SESSION['access_token'] = $access_token;
		// Let's get the user's info
		$user_info = $twitteroauth->get('account/verify_credentials');
		// Print user's info
		echo '<pre>';print_r($user_info);die;
    	$this->template->content = View::factory('user/info')
            ->bind('user', $user);

        // Load the user information
        $user = Auth::instance()->get_user();
         
        // if a user is not logged in, redirect to login page
        if (!$user)
        {
            Request::current()->redirect('user/login');
        }
    }
 
    public function action_create()
    {
        $this->template->content = View::factory('user/create')
            ->bind('errors', $errors)
            ->bind('message', $message);
             
        if (HTTP_Request::POST == $this->request->method())
        {          
            try {
         
                // Create the user using form values
                $user = ORM::factory('user')->create_user($this->request->post(), array(
                    'username',
                    'password',
                    'email'            
                ));
                 
                // Grant user login role
                $user->add('roles', ORM::factory('role', array('name' => 'login')));
                 
                // Reset values so form is not sticky
                $_POST = array();
                 
                // Set success message
                $message = "You have added user '{$user->username}' to the database";
                 
            } catch (ORM_Validation_Exception $e) {
                 
                // Set failure message
                $message = 'There were errors, please see form below.';
                 
                // Set errors using custom messages
                $errors = $e->errors('models');
            }
        }
    }
     
    public function action_login()
    {
        $this->template->content = View::factory('user/login')
            ->bind('message', $message);
          
        if (HTTP_Request::POST == $this->request->method())
        {
            // Attempt to login user
            $remember = array_key_exists('remember', $this->request->post()) ? (bool) $this->request->post('remember') : FALSE;
            $user = Auth::instance()->login($this->request->post('username'), $this->request->post('password'), $remember);
             
            // If successful, redirect user
            if ($user)
            {
                Request::current()->redirect('user/index');
            }
            else
            {
                $message = 'Login failed';
            }
        }
    }
    
	public function action_loginfb()
    {
    	$fbauth = FBAuth::instance();
    	
		try
		{
			$username = $fbauth->get('username');
			$email = $fbauth->get('email');
			$uid = $fbauth->get('uid');
			// Do something			
		}
		catch (Exception $e)
		{
			Request::current()->redirect($fbauth->login_url());
		}
    }
    
	public function action_logintw()
    {
    	$this->_config = Kohana::$config->load('twitter');
    	// Cria o objeto TwitterOAuth com as credenciais do cliente
		$connection = new TwitterOAuth($this->_config->get('consumer_key'), $this->_config->get('consumer_secret'));
   		// Requesting authentication tokens, the parameter is the URL we will be redirected to  
		//$request_token = $connection->getRequestToken($this->_config->get('callback_url'));
		$request_token = $connection->getRequestToken('http://localhost/rankitt/user/index');  
		  
		// Saving them into the session 
		session_start(); 
		$_SESSION['oauth_token'] = $request_token['oauth_token'];  
		$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];  
		  
		// If everything goes well..  
		if($connection->http_code==200){  
		    // Let's generate the URL and redirect  
		    $url = $connection->getAuthorizeURL($request_token['oauth_token']); 		   
		    header('Location: '. $url); 
		} else { 
		    // It's a bad idea to kill the script, but we've got to know when there's an error.  
		    die('Something wrong happened.');  
		}		
    }
     
    public function action_logout()
    {
        // Log user out
        Auth::instance()->logout();
         
        // Redirect to login page
        Request::current()->redirect('user/login');
    }
 
}